import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { logger } from '../utils'

// 页面组件
const Login = () => import('../pages/Login.vue')
const MachineInfo = () => import('../pages/MachineInfo.vue')
const DatabaseStatus = () => import('../pages/DatabaseStatus.vue')
const AlarmMonitor = () => import('../pages/AlarmMonitor.vue')
const MonitorConfig = () => import('../pages/MonitorConfig.vue')

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/alarm',
    name: 'AlarmMonitor',
    component: AlarmMonitor,
    meta: { requiresAuth: true, title: '监控告警' }
  },
  {
    path: '/database',
    name: 'DatabaseStatus',
    component: DatabaseStatus,
    meta: { requiresAuth: true, title: '数据库状态' }
  },
  {
    path: '/machines',
    name: 'MachineInfo',
    component: MachineInfo, 
    meta: { requiresAuth: true, title: '机器信息' }
  },
  {
    path: '/monitor-config',
    name: 'MonitorConfig',
    component: MonitorConfig,
    meta: { requiresAuth: true, title: '监控配置' }
  }
]

// 根据环境动态设置路由基础路径
const getRouterBase = () => {
  // 检查是否是nginx部署模式
  const isNginxDeploy = import.meta.env?.MODE === 'nginx'
  return isNginxDeploy ? '/monitor/' : '/'
}

// 创建路由实例
const router = createRouter({
  history: createWebHistory(getRouterBase()),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('authToken')
  
  logger.info('路由守卫触发', { to: to.path, from: from.path, hasToken: !!token })
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 金融监控系统`
  }
  
  // 认证检查
  if (to.meta.requiresAuth && !token) {
    logger.warn('需要认证但没有token，重定向到登录页')
    next('/login')
  } else if (to.path === '/login' && token) {
    // 已登录用户访问登录页，重定向到首页
    logger.info('已登录用户访问登录页，重定向到机器信息页')
    next('/machines')
  } else {
    logger.info('路由正常通过', { to: to.path })
    next()
  }
})

export default router